export default class Socket {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.isConnected = false;
    this.onConnected = null;
    this.onMessage = null;
    this.onError = null;
    this.onClosed = null;
	this.heartbeatTimer = null;
  }
 
  connect() {
    this.socket = uni.connectSocket({
      url: this.url,
      success: () => {
        console.log('WebSocket连接成功---来自util的消息');
      },
      fail: (error) => {
        console.error('WebSocket连接失败: ', error);
        if (typeof this.onError === 'function') {
          this.onError(error);
        }
      },
    });
 
    uni.onSocketOpen(() => { 
      this.isConnected = true;
      if (typeof this.onConnected === 'function') {
        this.onConnected();
      }
    });
 
    uni.onSocketMessage((result) => {
      if (typeof this.onMessage === 'function') {
        this.onMessage(result);
      }
    });
 
    uni.onSocketError((error) => {
      console.error('WebSocket发生错误: ', error);
      if (typeof this.onError === 'function') {
        this.onError(error);
      }
    });
 
    uni.onSocketClose(() => {
      if (typeof this.onClosed === 'function') {
        this.onClosed();
      }
    });
  }
	//开启心跳检测
	startHeartbeat(interval = 30000, message={type:88,data:{data:"heartbeat"}}) {
    //防抖机制，在第一次调用计时器的30s内不会开启新的计时器
		this.stopHeartbeat();
		this.heartbeatTimer = setInterval(() => {
		  this.send(JSON.stringify(message));
		  console.log("心跳检测执行到此")
		}, interval);
	  }
 
	  stopHeartbeat() {
		if (this.heartbeatTimer) {
		  clearInterval(this.heartbeatTimer);
		  this.heartbeatTimer = null;
		}
	  }
	  send(message) {
		if (this.isConnected) {
		  uni.sendSocketMessage({
			data: message,
		  });
		} else {
		  console.error('WebSocket未连接');
		}
	  }
 
	  close() {
		if (this.isConnected) {
		  uni.closeSocket();
		} else {
		  console.error('WebSocket未连接');
		}
	  }
	}